package cn.peifu.hrm.details;

import cn.peifu.hrm.constants.BaseConstants;
import cn.peifu.hrm.domain.Login;
import cn.peifu.hrm.domain.Permission;
import cn.peifu.hrm.domain.Tenant;
import cn.peifu.hrm.feign.SystemFeignClient;
import cn.peifu.hrm.mapper.LoginMapper;
import cn.peifu.hrm.mapper.PermissionMapper;
import cn.peifu.hrm.to.LoginInfoTo;
import cn.peifu.hrm.util.AjaxResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private LoginMapper loginMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private SystemFeignClient systemFeignClient;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Login login = loginMapper.selectByUsername(username);
        /*List<GrantedAuthority> permissions = new ArrayList<>();*/
        List<Permission> permissions = permissionMapper.selectPermissionsByUserId(login.getId());

        LoginInfoTo infoTo = new LoginInfoTo();
        //设置用户名、用户id、用户类型
        infoTo.setUsername(login.getUsername());
        infoTo.setUserId(login.getId());
        //如果是机构，查询权限
        if(login.getType().equals(BaseConstants.LoginConstants.TYPE_TENANT)){
            //调用feign查询机构信息
            AjaxResult ajaxResult = systemFeignClient.selectByLoginId(login.getId());
            if (ajaxResult == null && ajaxResult.getResultObj() == null){
                Tenant tenant = JSONObject.parseObject(JSONObject.toJSONString(ajaxResult.getResultObj()), Tenant.class);
                infoTo.setTenantId(tenant.getId());
                infoTo.setTenantName(tenant.getCompanyName());
            }
        }
        List<SimpleGrantedAuthority> authorityList = new ArrayList<>();
        //如果是前台用户，则不用查权限
        if (!login.getType().equals(BaseConstants.LoginConstants.TYPE_USER)){
            authorityList = permissions.stream().map(permission -> {
                return new SimpleGrantedAuthority(permission.getSn());
            }).collect(Collectors.toList());
        }

        Collection<SimpleGrantedAuthority> authorities = null;
        return new org.springframework.security.core.userdetails.User(
                JSON.toJSONString(infoTo),
                login.getPassword(),
                authorityList);
    }
}
